package com.heatup.apt.management.service.course.impl;

import com.baomidou.mybatisplus.mapper.*;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.heatup.apt.common.constants.ResourceContants;
import com.heatup.apt.common.dao.CourseStandardMapper;
import com.heatup.apt.common.dao.ResourceMapper;
import com.heatup.apt.management.service.course.CourseStandardService;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.ResourceModel;
import com.heatup.apt.model.course.CourseStandard;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by b3st9u on 16/9/23.
 */
@Service
public class CourseStandardServiceImpl implements CourseStandardService {
    @Autowired
    CourseStandardMapper courseStandardMapper;
    @Autowired
    ResourceMapper resourceMapper;

    @Override
    public Map<String, Object> queryCourseBaseList(int page, int limit) {
        Map<String, Object> map = new HashMap<>();
        int offset = 0;
        if (page > 1) {
            offset = (page-1) * limit;
        }
        RowBounds rowBounds = new RowBounds(offset, limit);
        List<CourseStandard> courseStandards = courseStandardMapper.selectPage(rowBounds,null);
        int count = courseStandardMapper.selectCount(null);
        int pageCount = 0;
        if (count % limit == 0) {
            pageCount = count / limit;
        } else {
            pageCount = count / limit + 1;
        }
        map.put("totalPage", pageCount);//总页数
        map.put("page", page);//当前页数
        map.put("size", limit);
        map.put("totalCount", count);//总个数
        map.put("courseList", courseStandards);
        return map;
    }

    /**
     * 根据标准课程ID查询标准课程
     * @param courseStandardId
     * @return
     */
    @Override
    public CourseStandard queryCourseStandardById(int courseStandardId) {
        if (courseStandardId <= 0) {
            return null;
        }
        CourseStandard courseStandard = courseStandardMapper.queryCourseStandardWithResourceById(courseStandardId);
        if (courseStandard != null && courseStandard.getResources().size() > 0) {
            List<Resource> resources = courseStandard.getResources();

            StringBuilder sCatePic = new StringBuilder();
            for(Resource resource: resources){
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("common_video") ) {
                    courseStandard.setUrl(resource.getUrl());
                    courseStandard.setLink(resource.getLink());
                }
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("common_category") ) {
                    if (sCatePic.length() <= 0) {
                        sCatePic.append(resource.getUrl());
                    } else {
                        sCatePic.append("," + resource.getUrl());
                    }
                }
            }
            if (sCatePic.length() > 0) {
                courseStandard.setCategoryPic(sCatePic.toString());
            }
        }
        return courseStandard;
    }

    @Override
    public List<Resource> queryCourseStandardResourceById(int courseStandardId) {
        ResourceExample resourceE = new ResourceExample();
        resourceE.or().andParentIdEqualTo(courseStandardId).andParentTypeEqualTo("4");
        List<Resource> list = resourceMapper.selectByExample(resourceE);
        return list;
    }

    /**
     * 根据课程Id查询课程对应图片视频
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, List<ResourceModel>> selectResourceByCourseId(int id) {
        ResourceExample resourceExample = new ResourceExample();
        resourceExample.or().andParentIdEqualTo(id).andParentTypeEqualTo("4");//查询图片&视频资源
        List<Resource> resources = resourceMapper.selectByExample(resourceExample);
        if (resources != null && resources.size() > 0) {
            Map<String, List<ResourceModel>> resourceMap = new HashMap<String, List<ResourceModel>>();
            for (Resource resource : resources) {
                List<ResourceModel> resourceModels = null;
                String type = ResourceContants.ResourceResTypeEnum.getResType(resource.getResType()).getTitle();
                if (!Strings.isNullOrEmpty(resource.getResKey()) && resource.getResKey().equals("common_video")) {
                    type = resource.getResKey();
                }
                if (resourceMap.containsKey(type)) {
                    resourceModels = resourceMap.get(type);
                } else {
                    resourceModels = Lists.newArrayList();
                }
                ResourceModel resourceModel = new ResourceModel();
                //resourceModel.setPreviewUrl(resource.getPreviewUrl());
                resourceModel.setTitle(resource.getTitle());
                resourceModel.setLink(resource.getLink());
                resourceModel.setUrl(resource.getUrl());
                resourceModel.setId(resource.getId());
                resourceModels.add(resourceModel);
                resourceMap.put(type, resourceModels);
            }
            return resourceMap;
        }
        return null;
    }

    /**
     * 根据课程ID 查询标准课程关联资源
     * @param id
     * @return
     */
    @Override
    public CourseStandard queryCourseStandardWithResourceById(int id) {

        CourseStandard courseStandard = courseStandardMapper.queryCourseStandardWithResourceById(id);
        if (courseStandard != null && courseStandard.getResources() != null && courseStandard.getResources().size() > 0) {
            StringBuilder sCatePic = new StringBuilder();

            for (Resource resource : courseStandard.getResources()) {
                if (StringUtils.isNotBlank(resource.getUrl()) && resource.getResKey().equalsIgnoreCase("common_video")) {
                    courseStandard.setUrl(resource.getUrl());
                    courseStandard.setLink(resource.getLink());
                }

                if (StringUtils.isNotBlank(resource.getUrl()) && resource.getResKey().equalsIgnoreCase("common_category")) {
                    if (sCatePic.length() <= 0) {
                        sCatePic.append(resource.getUrl());
                    } else{
                        sCatePic.append("," + resource.getUrl());
                    }
                }
            }
            if (sCatePic.length() > 0) {
                courseStandard.setCategoryPic(sCatePic.toString());
            }
        }
        return courseStandard;
    }

    /**
     * 标准课程保存
     * @param courseStandard
     * @return
     */
    @Override
    public boolean saveCourseStandard(CourseStandard courseStandard) {
       boolean result = false;
        if (courseStandard == null) {
            return result;
        }
        if(StringUtils.isNotBlank(courseStandard.getCourseAttr())){
            courseStandard.setCourseAttr(courseStandard.getCourseAttr().replaceAll(",","#"));
        }
        if (courseStandard.getId() != null) {
            courseStandard.setUpdatedTime(new Date());
            result = courseStandardMapper.updateSelectiveById(courseStandard) > 0;
            result = resourceMapper.deleteByCourseStandardId(courseStandard.getId()) > 0;
        } else {
            courseStandard.setCreatedTime(new Date());
            result = courseStandardMapper.insertSelective(courseStandard) > 0;
        }

        if (StringUtils.isNotBlank(courseStandard.getUrl())) {
            Resource videoResource;
            videoResource = new Resource();
            videoResource.setParentId(courseStandard.getId());
            videoResource.setParentType("4");
            videoResource.setResType("2");
            videoResource.setResKey("common_video");
            videoResource.setTitle("标准课程视频");
            videoResource.setUrl(courseStandard.getUrl());
            videoResource.setLink(courseStandard.getLink());
            resourceMapper.insertSelective(videoResource);
        }

        String catePic = courseStandard.getCategoryPic();
        if (StringUtils.isNotBlank(catePic)) {
            String[] catePics = catePic.split(",");
            Resource catePicResource;
            for (String pic : catePics) {
                catePicResource = new Resource();
                catePicResource.setParentId(courseStandard.getId());
                catePicResource.setParentType("4");
                catePicResource.setResType("1");
                catePicResource.setResKey("common_category");
                catePicResource.setTitle("标准课程类别硬照");
                catePicResource.setUrl(pic);
                resourceMapper.insertSelective(catePicResource);
            }
        }
        return result;
    }

    /**
     * 标准课程分页查询
     * @param paramsMap
     * @return
     */
    @Override
    public Map<String, Object> queryCourseStandardList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap();
        paramsMap.put("pageNo",(Integer)paramsMap.get("pageIndex") * (Integer)paramsMap.get("pageSize"));
        paramsMap.put("pageSize", paramsMap.get("pageSize"));
        resultMap.put("courseStandardList", courseStandardMapper.queryCourseStandardList(paramsMap));
        resultMap.put("courseStandardCount", courseStandardMapper.queryCourseStandardCount(paramsMap));
        return resultMap;
    }

    /**
     * 查询标准课程 ID NAME LIST
     *
     * @return
     */
    @Override
    public List<CourseStandard> queryAllCourseStandardIdAndName() {
        return courseStandardMapper.queryAllCourseStandardIdAndName();
    }

    /**
     * 标准课程 删除
     * @param courseStandardId
     * @return
     */
    @Override
    public int delCourseStandardById(int courseStandardId) {
        //resourceMapper.deleteByCourseStandardId(courseStandardId);
        CourseStandard courseStandard = courseStandardMapper.selectById(courseStandardId);
        if(courseStandard!=null){
            courseStandard.setStatus("4");
            courseStandard.setUpdatedTime(new Date());
            return courseStandardMapper.updateSelectiveById(courseStandard);
        }
        return 0;
    }

    @Override
    public int updateCourseStandard(CourseStandard courseStandard) {
        return courseStandardMapper.updateSelectiveById(courseStandard);
    }

    @Override
    public int insertCourseStandard(CourseStandard courseStandard) {
        return courseStandardMapper.insertSelective(courseStandard);
    }

    @Override
    public List<CourseStandard> queryAllCourseStandard() {
        EntityWrapper<CourseStandard> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("status = {0}","1");
        return courseStandardMapper.selectList(entityWrapper);
    }
}
